package org.haifi.game.remoting.impl;

import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.haifi.game.model.GameServer;
import org.haifi.game.remoting.GameUserRemotingManager;
import org.haifi.game.remoting.RemotingFactory;
import org.haifi.service.GameUserManagerTest1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor;
import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean;
import org.springframework.remoting.httpinvoker.HttpInvokerRequestExecutor;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;

/**
 * 远程方法调用接口的factory bean.
 * 
 * 内部会根据url缓存生成的远程方法的接口
 * 
 * @author joycube2
 * 
 */
@Component
public class RemotingFactoryImpl implements RemotingFactory {
	/**
	 * 缓存生成的远程接口
	 */
	private Map<String, Object> gameUserRemotingCache = Maps.newConcurrentMap();

	public GameUserRemotingManager getGameUserRemotingManager(
			GameServer gameServer) {
		return (GameUserRemotingManager) generateRemotingManager(
				gameUserRemotingCache, gameServer.getIp(), "/GameUserService",
				GameUserRemotingManager.class);
	}

	private Object generateRemotingManager(Map<String, Object> cache,
			String url, String serverName, Class clazz) {
		GameUserRemotingManager obj = (GameUserRemotingManager) cache.get(url);
		if (obj != null) {
			return obj;
		}
		if (!url.endsWith("/")) {
			url += "/";
		}
		url = "http://" + url + PATH + serverName;
		HttpInvokerProxyFactoryBean bean = new HttpInvokerProxyFactoryBean();
		bean.setServiceUrl(url);
		bean.setServiceInterface(clazz);
		bean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor);
		bean.afterPropertiesSet();
		obj = (GameUserRemotingManager) bean.getObject();
		return obj;
	}

	private static final String PATH = "gr";
	@Autowired
	private HttpInvokerRequestExecutor httpInvokerRequestExecutor;

	private static final Log log = LogFactory.getLog(RemotingFactoryImpl.class);
}
